<?php
class Model_Cart extends App_Model_Entity
{
	protected $_data = array(
	   'id'         => null,
	   'user_id'    => null,
	   'products' => null,
	   'total'
	);
	
	public function __get($field)
	{
	    switch ($field)
	    {
	        case 'products' : 
	            return $this->_getProducts();
	            break;
	        case 'total' : 
	            return $this->_getTotal();
	            break;
	        default: 
	            return parent::__get($field);
	            break;
	    }
	}
	protected function _getProducts()
	{
	      $mapper = new Model_Cart_Mapper();
	      
		  if($this->user_id !== null) {
    		  if($this->_data['products'] === null){
    		      $products = $mapper->getProducts($this->user_id);
    		      $this->_data['products'] = $products;
    		  }
		  }
		  return $this->_data['products'];
	}
	
	public function addProduct(Model_Product_Cart $product)
	{
		foreach($this->products as $productInCart){
		    if($product->id == $productInCart->id){
		        return false;
		    }
		}
		
		$date = new Zend_Date();
		$product->date = $date->getIso();
		$this->_data['products'][] = $product;
	}
	
	public function removeProduct(Model_Product_Cart $product)
	{
        $i =0;
	    foreach($this->products as $key => $productInCart){
            if($product->id == $productInCart->id){
                unset($this->_data['products'][$key]);
            }
        $i++;
        }

	}
	
	protected function _getTotal()
	{
	    foreach($this->products as $product){
	        if($product->price != 0)
	        {
	            $total += $product->price;
	        }
	    }
	    return $total;
	}
}